<!-- 分类参数 -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert title="注意！只允许为第三级分类设置相关参数" type="warning" :closable='false' show-icon >
      </el-alert>
      <el-row class="castype">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            size="msmall"
            clearable
            v-model="paramsSelectCasKeysValue"
            :options="parentCateList"
            :props="paramsCascaderProps"
            @change="catCascaderChange">
          </el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加参数</el-button>
          <el-table :data="manyTabList" border stripe >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag size="medium" v-for="(item,index) in scope.row.attr_vals"
                :key="index" :closable="true" @close="handleTagCloseClick(index,scope.row)">{{item}}</el-tag>
                <!-- 添加新标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">添加</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="editBtnClick(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteBtnClick(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addDialogVisible=true">添加属性</el-button>
          <el-table :data="onlyTabList" border stripe >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag size="medium" v-for="(item,index) in scope.row.attr_vals"
                :key="index" :closable="true" @close="handleTagCloseClick(index,scope.row)">{{item}}</el-tag>
                <!-- 添加新标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">添加</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" @click="editBtnClick(scope.row)">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete" @click="deleteBtnClick(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="'添加'+getDialogTitle" :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <!-- dialog主题区域 -->
      <el-form :model="addForm" :rules="addFormRules"
        ref="addFormRef" label-width="100px">
        <el-form-item :label="getDialogTitle+':'" prop="attr_name" >
          <el-input v-model="addForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialogClick">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改'+getDialogTitle" :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!-- dialog主题区域 -->
      <el-form :model="editForm" :rules="addFormRules"
        ref="editFormRef" label-width="100px">
        <el-form-item :label="getDialogTitle+':'" prop="attr_name" >
          <el-input v-model="editForm.attr_name" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editDialogClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  created () {
    this.getParamsList()
  },
  data () {
    return {
      // 分类list
      paramsList: [],
      // 级联选择器绑定数据
      parentCateList: [],
      // 级联选择器选择的结果数据
      paramsSelectCasKeysValue: [],
      // 级联选择器相关属性设定
      paramsCascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 激活的tab标签名称
      activeName: 'many',
      manyTabList: [],
      onlyTabList: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 10,
            message: '长度在1-10之间',
            trigger: 'blur'
          }
        ]
      },
      editDialogVisible: false,
      editForm: {}
    }
  },
  methods: {
    // 获取父级分类列表
    async getParamsList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败')
      }
      this.parentCateList = res.data
    },
    // 级联选择改变事件
    catCascaderChange () {
      // 将最后一个赋值到pid
      this.getParamsData()
    },
    // tab 标签点击事件
    handleTabClick () {
      this.getParamsData()
    },
    async getParamsData () {
      if (this.paramsSelectCasKeysValue.length < 3) {
        this.paramsSelectCasKeysValue = []
        this.manyTabList = []
        this.onlyTabList = []
      } else {
        const { data: res } = await this.$http.get(`categories/${this.getCatThreeID}/attributes`, {
          params: { sel: this.activeName } })
        if (res.meta.status !== 200) {
          return this.$message.error('获取商品分类详细信息失败')
        }
        console.log(res.data)
        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })
        if (this.activeName === 'many') {
          this.manyTabList = res.data
        } else {
          this.onlyTabList = res.data
        }
      }
    },
    addDialogClick () {
      this.$refs.addFormRef.validate(async (isTrue, obj) => {
        if (!isTrue) return
        const { data: res } = await this.$http.post(`categories/${this.getCatThreeID}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('添加参数失败')
          return
        }
        this.$message.success('添加参数成功！')
        this.addDialogVisible = false
        this.getParamsData()
      })
    },
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    async editBtnClick (params) {
      const { data: res } = await this.$http.get(`categories/${this.getCatThreeID}/attributes/${params.attr_id}`, {
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) {
        this.$message.error('获取详细参数失败')
        return
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    editDialogClick () {
      this.$refs.editFormRef.validate(async (isTrue, obj) => {
        if (!isTrue) return
        const { data: res } = await this.$http.put(`categories/${this.getCatThreeID}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        console.log(res)
        if (res.meta.status !== 201) {
          this.$message.error('修改参数失败')
          return
        }
        this.$message.success('修改参数成功！')
        this.editDialogVisible = false
        this.getParamsData()
      })
    },
    // 删除按钮
    async deleteBtnClick (params) {
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      let { data: res } = await this.$http.delete(`categories/${this.getCatThreeID}/attributes/${params.attr_id}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除用户失败')
      }
      this.$message.success('删除用户成功')
      this.getParamsData()
    },
    // 添加tag标签的确定取消事件
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
      } else {
        // chuli
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue = ''
        row.inputVisible = false
        this.saveTagAttrVals(row)
      }
    },
    // tag显示
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除对应tag参数属性
    handleTagCloseClick (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveTagAttrVals(row)
    },
    async saveTagAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.getCatThreeID}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) {
        return this.$message.error('添加标签失败')
      }
      this.$message.success('添加标签成功')
    }
  },
  computed: {
    // 判断级联是否是第三级btn显示或隐藏
    isBtnDisabled () {
      if (this.paramsSelectCasKeysValue.length !== 3) {
        return true
      }
      return false
    },
    getCatThreeID () {
      if (this.paramsSelectCasKeysValue.length === 3) {
        return this.paramsSelectCasKeysValue[2]
      }
      return null
    },
    getDialogTitle () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}

</script>
<style lang='less' scoped>
.el-cascader{
  margin-top: 15px;
}
.castype{
  margin-top: 15px 0;
}
.el-tag{
  margin: 5px;
}
.input-new-tag{
  width: 140px;
}
</style>
